<template>
	<div class="app-container">
		<el-form class="queryForms" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="85px">
			<el-form-item label="工作流名称" prop="workflowName">
				<el-input maxlength="20" show-word-limit v-model="queryParams.workflowName" placeholder="请输入工作流名称"
					clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['erp:workflow:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
					v-hasPermi="['erp:workflow:remove']">删除</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList" perm="erp:workflow:list"></right-toolbar>
		</el-row>

		<div :class="eleTabTop <= 85 ? 'eleTab' : ''" class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="workflowList"
				@selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" prop="id" type="index" width="55" />
				<el-table-column label="工作流名称" prop="workflowName" min-width="150" :show-overflow-tooltip="true" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
					width="200">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-setting" @click="handleSetting(scope.row)"
							v-hasPermi="['erp:workflow:setting']">设置步骤</el-button>
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
							v-hasPermi="['erp:workflow:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
							v-hasPermi="['erp:workflow:remove']">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination83" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改工作流对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="650px" append-to-body v-dialogDrag>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="工作流名称" prop="workflowName">
					<el-input v-model="form.workflowName" placeholder="请输入工作流名称" maxlength="20" show-word-limit />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="工作流步骤" :visible.sync="openflow" width="900px" append-to-body v-dialogDrag>
			<div style="min-height: 20vh; max-height: 70vh; overflow-y: scroll; padding-right: 10px">
				<el-button type="primary" style="float: right" @click="addworkSteps"
					v-if="disables == '0'">增加工作流步骤</el-button>
				<div style="margin-top: 35px">
					<el-timeline>
						<el-timeline-item
							:timestamp="`${item.approverType == '1' || item.approverType == '3' ? '审批人' : '审批角色'}：${item.approverName ? item.approverName : ''}`"
							placement="top" v-for="(item, index) in stepList" :key="index">
							<el-card>
								<div class="showdelete">
									<div class="showInfo">
										<div class="showPer">角色类型：</div>
										<el-select :disabled="disables == '0' ? false : true"
											v-model="item.approverType" style="width: 200px"
											@change="seletRole($event, index)" placeholder="请选择">
											<el-option v-for="type in roleTypes" :value="type.id" :label="type.name"
												:key="type.id + '_' + index"></el-option>
										</el-select>
									</div>
									<div>
										<el-button type="primary" size="mini" @click="deleteSteps(index)"
											v-if="disables == '0'">删除</el-button>
									</div>
								</div>
								<div class="showInfo" v-show="item.approverType !== '3'">
									<div class="showPer">审核人：</div>
									<el-select :disabled="disables == '0' ? false : true" v-model="item.approverId"
										style="width: 200px" placeholder="请选择" @change="seletapprover($event, index)"
										:multiple="item.approverType == '2'" :collapse-tags="item.approverType == '2'">
										<template v-if="item.approverType == '1'">
											<el-option v-for="per in perList" :value="per.approverId"
												:label="per.approverName"
												:key="per.approverId + '_' + index"></el-option>
										</template>
										<template v-if="item.approverType == '2'">
											<el-option v-for="role in roleList" :value="role.approverId"
												:label="role.approverName"
												:key="role.approverId + '_' + index"></el-option>
										</template>
									</el-select>
								</div>
								<div class="showInfo">
									<div class="showPer">签字状态：</div>
									<el-select :disabled="disables == '0' ? false : true" v-model="item.signatureStatus"
										placeholder="请选择" style="width: 200px">
										<el-option v-for="dict in dict.type.default_single_status" :key="dict.value"
											:label="dict.label" :value="dict.value"></el-option>
									</el-select>
								</div>
							</el-card>
						</el-timeline-item>
					</el-timeline>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFlow">确 定</el-button>
				<el-button @click="openflow = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { getUserList, roleDown, getcolumn } from "@/api/selectList"
import { listWorkflow, getWorkflow, delWorkflow, addWorkflow, updateWorkflow, installflow, workflowStep } from "@/api/workflow/workflow"
export default {
	name: "Workflow_menu",
	dicts: ["default_single_status"],
	data() {
		return {
			eleTabTop: 0, //表格容器距浏览器顶部距离
			disables: "0",
			//人员数据
			perList: [],
			//角色数据
			roleList: [],
			roleTypes: [
				{
					id: "1",
					name: "人员"
				},
				{
					id: "2",
					name: "角色"
				},
				{
					id: "3",
					name: "部门领导"
				}
			],
			// 步骤列表
			stepList: [],
			openflow: false,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 工作流表格数据
			workflowList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				workflowName: null
			},
			// 表单参数
			form: {},
			//当前操作的工作流
			workflowTypeId: "",
			// 表单校验
			rules: {
				workflowName: [{ required: true, message: "工作流名称不能为空", trigger: "blur" }]
			}
		}
	},
	created() {
		this.getSize()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination83" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == '操作') {
				return;
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		//工作流删除按钮操作
		deleteSteps(index) {
			this.stepList.forEach((item, index1) => {
				if (index1 > index) {
					item.sequenceSteps = item.sequenceSteps - 1
				}
			})
			this.stepList.splice(index, 1)
		},
		//增加工作流步骤的操作
		addworkSteps() {
			this.stepList.push({
				approverType: "",
				approverId: [],
				signatureStatus: "",
				approverName: "",
				sequenceSteps: this.stepList.length + 1
			})
		},
		//保存工作流
		submitFlow() {
			let flag = true
			this.stepList.forEach(item => {
				item.workflowType = this.workflowTypeId
				if (!item.approverType || item.approverId.length == 0 || !item.signatureStatus) {
					this.$modal.msgError("请先将数据填写完整")
					flag = false
				}
			})
			if (flag) {
				const params = this.stepList.map(item => {
					return {
						...item,
						approverId: Array.isArray(item.approverId) ? item.approverId.join(",") : item.approverId.toString()
					}
				})
				installflow(params).then(res => {
					this.openflow = false
					this.$modal.msgSuccess("设置成功")
				})
			}
		},
		//审核人选择器的change
		seletapprover(e, index) {
			if (typeof e == "number" || typeof e == "string") {
				this.perList.forEach(item => {
					if (e == item.approverId) {
						this.stepList[index].approverName = item.approverName
					}
				})
			} else {
				let str = ""
				this.roleList.forEach(item => {
					if (e.includes(item.approverId)) {
						str += item.approverName + "，"
					}
				})
				this.stepList[index].approverName = str.slice(0, -1)
			}
		},
		//角色类型的change
		seletRole(e, index) {
			if (e === "1") {
				this.stepList[index].approverId = this.perList.length ? this.perList[0].approverId : ""
				this.stepList[index].approverName = this.perList.length ? this.perList[0].approverName : ""
			} else if (e === "2") {
				this.stepList[index].approverId = this.roleList.length ? [this.roleList[0].approverId] : ""
				this.stepList[index].approverName = this.roleList.length ? this.roleList[0].approverName : ""
			} else {
				this.stepList[index].approverId = Math.random() + 1.001
				this.stepList[index].approverName = "部门领导"
			}
		},
		//获取人员的下拉选择数据
		getuserList() {
			getUserList().then(res => {
				this.perList = res.rows.map(element => {
					return {
						approverId: element.userId,
						approverName: element.nickName
					}
				})
			})
		},
		//获取角色的下拉选择数据
		getroleList() {
			roleDown().then(res => {
				this.roleList = res.rows.map(element => {
					return {
						approverId: element.roleId,
						approverName: element.roleName
					}
				})
			})
		},
		//根据角色类型获取审批人的最新数据
		getSelectList(e) {
			// 1 人员    2角色
			if (e === "1") {
				this.getuserList()
			} else if (e === "2") {
				this.getroleList()
			} else {
				this.getuserList()
				this.getroleList()
			}
		},
		//点击设置步骤
		handleSetting(row) {
			//保存当前操作的工作流id
			this.workflowTypeId = row.id
			this.getSelectList("all")
			this.disables = row.alterState
			workflowStep({ workflowType: row.id }).then(res => {
				// 想法   数据组合后进行过滤  （考虑key值重复）
				res.rows.forEach(item => {
					if (item.approverType == '2') {
						if (item.approverId.indexOf(",") == -1) {
							item.approverId = [Number(item.approverId)]
						} else {
							item.approverId = item.approverId.split(",").map(Number)
						}
					} else {
						item.approverId = Number(item.approverId)
					}
					item.signatureStatus = item.signatureStatus + ""
				})
				this.stepList = res.rows
				this.openflow = true
			})
		},
		/** 查询工作流列表 */
		getList() {
			this.loading = true
			listWorkflow(this.queryParams).then(response => {
				this.workflowList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				workflowName: null,
				remark: null
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = "添加工作流"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getWorkflow(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改工作流"
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.id != null) {
						updateWorkflow(this.form).then(response => {
							this.$modal.msgSuccess("修改成功")
							this.open = false
							this.getList()
						})
					} else {
						addWorkflow(this.form).then(response => {
							this.$modal.msgSuccess("新增成功")
							this.open = false
							this.getList()
						})
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除工作流数据项？")
				.then(function () {
					return delWorkflow(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"erp/workflow/export",
				{
					...this.queryParams
				},
				`workflow_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>
<style scoped lang="scss">
.showdelete {
	display: flex;
	justify-content: space-between;
}

.showInfo {
	display: flex;
	align-items: center;
	margin-bottom: 8px;

	.showPer {
		width: 80px;
	}
}
</style>
